var express = require('express');
var router = express.Router();
var db_config = require('../conn');

/* GET home page. */

/*router.use(function (req, res, next) {
	if(req.session.is_login == true){
		username = req.session.username;
		next();
	}else{
		username = null;
	}
});*/


router.get('/', function(req, res, next) {
	var username = req.session.username;
	console.log(username);
	var sql = 'select * from news order by news.id desc limit 60';
	conn.query(sql,function(err,rows,fields){
		var news = rows;
		conn.query('select * from message order by message.id desc limit 6',function(err,rows,fields){
			var message = rows;
			res.render('index', { title: 'OSChina',
				news: news,
				username: username,
				message: message
			});
		})
	})
});


router.get('/signout', function(req, res, next) {
	req.session.destroy();
    res.redirect('/');
})

router.post('/message',function(req,res,next){
	var d = new Date();
	var time = d.getHours()+':'+d.getMinutes();
/*	if (username==undefiend) {
		username = Math.floor(Math.random()*10000);
	}*/
	var name = req.session.username
	if (req.session.username==undefined || req.session.username =="" ) {
		name = '路人'+ Math.floor(Math.random()*10000);
	}
	var sql = 'insert into message values (null,"'+name+'","'+req.body.content+'","'+time+'")';
	conn.query(sql,function(err,rows,fields){
		res.redirect('/');
	})
})

router.get('/messageBoard',function(req, res, next){
	conn.query('select * from message order by id desc',function(err,rows,fields){
		res.render('messageBoard', { title: '更多动弹',
									message: rows,
									username: req.session.username
								});
	})
})
router.get('/delmessage',function(req, res, next){
	var sql = 'DELETE from message where id="'+req.query.id+'"';
	conn.query(sql,function(err,rows,fields){
		res.redirect('/messageBoard')
	})
})
router.post('/addmessage',function(req, res, next){
	var d = new Date();
	var time = d.getHours()+':'+d.getMinutes();
	if (req.session.username==undefined) {
		var name = '路人'+ Math.floor(Math.random()*10000);
	}else{
		var name = req.session.username;
	}
	var sql = 'insert into message values (null,"'+name+'","'+req.body.content+'","'+time+'")'
	conn.query(sql,function(err,rows,fields){
		res.redirect('/messageBoard')
	})
})

module.exports = router;
